import type { UserItem } from '@/services/system/types';
import { addUser, updateUser, removeUser, resetPwd } from '@/services/system/user';
import { message } from 'antd';

/**
 * 添加用户
 *
 * @param fields
 */
export const handleAdd = async (fields: UserItem) => {
  const hide = message.loading('正在新增用户');

  try {
    await addUser({ ...fields });
    hide();
    message.success('用户添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('用户添加失败，请重试！');
    return false;
  }
};

/**
 * 更新用户
 *
 * @param fields
 */
export const handleUpdate = async (fields: UserItem, currentRow?: UserItem) => {
  const hide = message.loading('正在更新用户');

  try {
    await updateUser({
      ...currentRow,
      ...fields,
    });
    hide();
    message.success('用户更新成功');
    return true;
  } catch (error) {
    hide();
    message.error('用户更新失败，请重试');
    return false;
  }
};

/**
 * 删除用户
 *
 * @param selectedRows
 */
export const handleRemove = async (selectedRows: UserItem[]) => {
  const hide = message.loading('正在删除用户');
  if (!selectedRows) return true;

  try {
    await removeUser(selectedRows.map((row) => row.id));
    hide();
    message.success('用户删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('用户删除失败，请重试');
    return false;
  }
};

/**
 * 重置密码
 *
 * @param selectedRows
 * @returns
 */
export const handleResetPwd = async (selectedRows: UserItem[]) => {
  const hide = message.loading('正在重置用户密码');
  if (!selectedRows) return true;

  try {
    await resetPwd(selectedRows.map((row) => row.id));
    hide();
    message.success('重置用户密码成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('重置用户密码失败，请重试');
    return false;
  }
};
